package WordCount;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

//批处理的WordCount程序
public class WordCountTest01 {
    public static void main(String[] args) throws Exception {
        //创建执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        //从文件中读取数据
        String inputPath = "E:\\IDEA\\IntelliJ IDEA 2019.1\\bm\\FlinkTest\\src\\main\\resources\\WordCount.txt";
        //dataSource其实就是一个dataSet
        DataSource<String> stringDataSource = env.readTextFile(inputPath);

        //对数据集来进行处理
        DataSet<Tuple2<String, Integer>> result = stringDataSource.flatMap(new MyFlatMapper())//按照空格来进行分词
                .groupBy(0)//按照第一个位置来进行分组
                .sum(1);//按照第二个位置的元素来进行聚合

        result.print();
    }

    //自定义类来实现FlatMapFunction接口
    //第一个String是输入的数据类型
    //第二个就是输出的数据类型
    public static class MyFlatMapper implements FlatMapFunction<String, Tuple2<String, Integer>> {

        @Override
        public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
            //按照空格来进行分词
            String[] words = s.split(" ");
            //遍历所有word包装成二元组输出
            for (String word : words) {
                collector.collect(new Tuple2<>(word, 1));
            }
        }
    }
}
